package com.aliyun.messagemgt.util;

import com.google.gson.Gson;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * Http工具类
 *
 * @author
 */
public class HttpUtils {

    private static final String ACCEPT = "*/*";
    private static final String CONNECTION = "Keep-Alive";
    private static final String USER_AGENT = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)";
    private static final String CONTENT_TYPE = "application/json; charset=utf-8";


    private static final Logger logger = LoggerFactory.getLogger(HttpUtils.class);

    /**
     * 向指定URL发送GET方法的请求
     */
    public static String sendGet(String url, Map<String, String> param, Map<String, String> headerParam) {

        CloseableHttpClient client = HttpClientBuilder.create().build();
        HttpGet httpGet = new HttpGet();

        String resultJson = "";
        try {
            //设置头部
            httpGet.setHeader("accept", ACCEPT);
            httpGet.setHeader("connection", CONNECTION);
            httpGet.setHeader("user-agent", USER_AGENT);
            httpGet.setHeader("Content-type", CONTENT_TYPE);
            if (headerParam != null) {
                for (Map.Entry<String,String> entry : headerParam.entrySet())  {
                    httpGet.setHeader(entry.getKey(), entry.getValue());
                }
            }
            //设置参数
            StringBuilder paramStr = new StringBuilder();
            if (param != null) {
                for (Map.Entry<String,String> entry : param.entrySet())  {
                    httpGet.setHeader(entry.getKey(), entry.getValue());
                    paramStr.append("&").append(entry.getKey()).append("=").append(entry.getKey());
                }
                url = url + "?" + paramStr.substring(1);
            }
            httpGet.setURI(new URI(url));

            // 发送请求
            HttpResponse httpResponse = client.execute(httpGet);

            // 获取返回的数据
            HttpEntity entity = httpResponse.getEntity();
            byte[] body = EntityUtils.toByteArray(entity);
            resultJson = new String(body, StandardCharsets.UTF_8);
        } catch (Exception e) {
            logger.error("发送GET请求出现异常！", e);
        }
        return resultJson;
    }

    /**
     * 向指定URL发送POST方法的请求
     */
    public static String sendPost(String url, Map<String, String> param, Map<String, String> headerParam) {
        Gson gson = new Gson();
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            //打开和URL之间的连接  
            URLConnection conn = realUrl.openConnection();
            //设置通用的请求属性  
            conn.setRequestProperty("accept", ACCEPT);
            conn.setRequestProperty("connection", CONNECTION);
            conn.setRequestProperty("user-agent", USER_AGENT);
            conn.setRequestProperty("Content-type", CONTENT_TYPE);
            //封装头部信息
            if (headerParam != null) {
                for (Map.Entry<String,String> entry : headerParam.entrySet())  {
                    conn.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }
            //发送POST请求必须设置如下两行  
            conn.setDoOutput(true);
            conn.setDoInput(true);
            //获取URLConnection对象对应的输出流  
            out = new PrintWriter(conn.getOutputStream());
            //发送请求参数  
            out.print(gson.toJson(param));
            //flush输出流的缓冲  
            out.flush();
            //定义BufferedReader输入流来读取URL的响应  
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += "" + line;
            }
        } catch (Exception e) {
            logger.error("发送POST请求出现异常！", e);
        }
        //使用finally块来关闭输出流、输入流  
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                logger.error("finally:", ex);

            }
        }
        return result;
    }


    public static String callbackInvoke(String url, String paramJson, Map<String, String> headerParam) {
        PrintWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        try {
            URL realUrl = new URL(url);
            //打开和URL之间的连接  
            URLConnection conn = realUrl.openConnection();
            //设置通用的请求属性  
            conn.setRequestProperty("accept", ACCEPT);
            conn.setRequestProperty("connection", CONNECTION);
            conn.setRequestProperty("user-agent", USER_AGENT);
            conn.setRequestProperty("Content-type", CONTENT_TYPE);
            //封装头部信息
            if (headerParam != null) {
                for (Map.Entry<String,String> entry : headerParam.entrySet())  {
                    conn.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }
            //发送POST请求必须设置如下两行  
            conn.setDoOutput(true);
            conn.setDoInput(true);
            //获取URLConnection对象对应的输出流  
            out = new PrintWriter(conn.getOutputStream());
            //发送请求参数  
            out.print(paramJson);
            //flush输出流的缓冲  
            out.flush();
            //定义BufferedReader输入流来读取URL的响应  
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
        } catch (Exception e) {
            logger.error("发送POST请求出现异常:", e);
        }
        //使用finally块来关闭输出流、输入流  
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                logger.error(" callbackInvoke finally:", ex);
            }
        }
        return result.toString();
    }

}
